<?php

/**
 * Joomla! 1.5 component arts_curriculum
 * @package    arts_curriculum
 * @subpackage
 * @author     Chris Borkowski {@link http://www.guggenheim.org}
 * @author     Created on 31-August-2009
 * @author     Modified on 25-January-2009
 */

// no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );


jimport( 'joomla.application.component.controller' );
require_once( JPATH_COMPONENT.DS.'helpers'.DS.'helper.php' );
/**
 * Arts_curriculum Controller
 *
 * @package Arts_curriculum
 */
class Arts_curriculumControllerItems extends JController
{
	function __construct()
	{
		parent::__construct();
		// Register Extra tasks
		//$this->registerTask( 'add', 'display' );
		//$this->registerTask( 'edit', 'display' );
	    $this->registerTask('unpublish', 'publish');
		$this->registerTask( 'edit', 'add');
	
	}
	
	function display()
	{
		$view = JRequest::getVar('view');
		
		if (!$view) {
			JRequest::setVar('view', 'arts_curriculum');
			JRequest::setVar( 'layout', 'default' );
		
		}

		parent::display();
	}
	
   function edit()
	{
		JRequest::setVar('view', 'item');
        JRequest::setVar( 'layout', 'form' );
        $model = $this->getModel('item');
        $model = $this->getModel('item');
		$model->checkout();
		$this->display();
	}
	
	function add()
	{
		JRequest::setVar('view', 'item');
		JRequest::setVar( 'layout', 'form' );
		$model = $this->getModel('item');
		$model->checkout();

		$this->display();
	}	

			
// 	function display( )
// 	{
// 		switch($this->getTask())
// 		{
// 			case 'add' :
// 				{
// 					JRequest::setVar( 'hidemainmenu', 1 );
// 					JRequest::setVar( 'layout', 'form' );
// 					JRequest::setVar( 'view' , 'item');
// 					JRequest::setVar( 'edit', false );
// 					// Checkout the item
// 					$model = $this->getModel('item');
// 					$model->checkout();
// 				} break;
// 			case 'edit' :
// 				{
// 					JRequest::setVar( 'hidemainmenu', 1 );
// 					JRequest::setVar( 'layout', 'form' );
// 					JRequest::setVar( 'view' , 'item');
// 					JRequest::setVar( 'edit', true );
// 					// Checkout the item
// 					$model = $this->getModel('item');
// 					$model->checkout();
// 				} break;
// 		}
// 		parent::display();
// 	}
	
	function store()
	{
		$post = JRequest::get('post');
		$cid = JRequest::getVar( 'cid', array(0), 'post', 'array' );
		$post['id'] = (int)$cid[0];
		$this->id = $post['id'] ;
		
		//$post['text'] = JRequest::getVar('text', '', 'post', 'string', JREQUEST_ALLOWRAW);
		$post['main_body'] = JRequest::getVar( 'main_body', '', 'post', 'string', JREQUEST_ALLOWRAW );
		$post['view_n_dis'] = JRequest::getVar( 'view_n_dis', '', 'post', 'string', JREQUEST_ALLOWRAW );
		$post['further_reading'] = JRequest::getVar( 'further_reading', '', 'post', 'string', JREQUEST_ALLOWRAW );
		$post['additional_resources'] = JRequest::getVar( 'additional_resources', '', 'post', 'string', JREQUEST_ALLOWRAW );
		$post['vocabulary'] = JRequest::getVar( 'vocabulary', '', 'post', 'string', JREQUEST_ALLOWRAW );
		// image caps
		$post['imgcap1'] = JRequest::getVar( 'imgcap1', '', 'post', 'string', JREQUEST_ALLOWRAW );
		$post['imgcap2'] = JRequest::getVar( 'imgcap2', '', 'post', 'string', JREQUEST_ALLOWRAW );
		$post['imgcap3'] = JRequest::getVar( 'imgcap3', '', 'post', 'string', JREQUEST_ALLOWRAW );
		$post['imgcap4'] = JRequest::getVar( 'imgcap4', '', 'post', 'string', JREQUEST_ALLOWRAW );
		
		$subject = JRequest::getVar('subject', array(), 'post', 'array');
		if (is_array( $subject )) {
   		$post['subject'] = implode( ",", $subject );
		}
		
		$medium = JRequest::getVar('medium', array(), 'post', 'array');
		if (is_array( $medium )) {
   		$post['medium'] = implode( ",", $medium );
		}
		
		
		$model = $this->getModel('item');
		if ($model->store($post)) {
			$this->msg = JText::_( 'Item Saved !');
		} else {
			$this->msg = JText::_( 'Error Saving Item !' );
		}
		
		//let's handel the uploads - ugly but's it 's my first uploader
		
		$file = JRequest::getVar( 'imagefile1', '', 'files', 'array' );

		if(isset($file['name']) && $file['name'] != '')
		{	
			jimport('joomla.filesystem.file');
			
			$safe = JFile::makesafe($file['name']);
			$bads = array(" ", "?", "*", "+", "@", "#", "%", "$", "!", "&");
			$cleaned = str_replace($bads, "_", $safe);
			$filename = JPATH_SITE . DS . 'images' . DS . 'content' . DS . 'arts_curriculum' . DS . 'masters'. DS. $cleaned;	
			// make a dupe for dloads
			$dest = JPATH_SITE . DS . 'images' . DS . 'content' . DS . 'arts_curriculum' . DS . 'dloads'. DS. $cleaned;
			JFile::copy($filename, $dest);	
					
			if (!JFile::upload($file['tmp_name'], $filename)) {
				$this->msg = JText::_( 'Life is bad and the upload failed, check to make sure that /images/content/arts_curriculum/images/masters exists and is writable' );
				return;
			}
			
			// were' in the file system so pass to thumbmaker &  upadte the DB	
			$image_to_make = & $cleaned;
			thumbMaker($image_to_make);
			
					
			$db =& JFactory::getDBO();
			$query = "UPDATE #__arts_curriculum SET image1 = '$cleaned' WHERE id = $this->id ";
			$db->setQuery( $query );
			if (!$db->query()) {
				echo "<script> alert('".$db->getErrorMsg()."'); window. history.go(-1); </script>\n";
			}

				
		}
		
		
		$file2 = JRequest::getVar( 'imagefile2', '', 'files', 'array' );

		if(isset($file2['name']) && $file2['name'] != '')
		{	
			jimport('joomla.filesystem.file');
			
			$safe2 = JFile::makesafe($file2['name']);
			$bads = array(" ", "?", "*", "+", "@", "#", "%", "$", "!", "&");
			$cleaned2 = str_replace($bads, "_", $safe2);
			$filename2 = JPATH_SITE . DS . 'images' . DS . 'content' . DS . 'arts_curriculum' . DS . 'masters'. DS. $cleaned2;	
			// make a dupe for dloads
			$dest = JPATH_SITE . DS . 'images' . DS . 'content' . DS . 'arts_curriculum' . DS . 'dloads'. DS. $cleaned2;
			JFile::copy($filename2, $dest);	
			
			if (!JFile::upload($file2['tmp_name'], $filename2)) {
				$this->msg = JText::_( 'Life is bad and the upload failed, check to make sure that /images/content/arts_curriculum/images/masters exists and is writable' );
				return;
			}
			// were' in the file system so upadte the DB		
			$db =& JFactory::getDBO();
			$query = "UPDATE #__arts_curriculum SET image2 = '$cleaned2' WHERE id = $this->id ";
			$db->setQuery( $query );
			if (!$db->query()) {
				echo "<script> alert('".$db->getErrorMsg()."'); window. history.go(-1); </script>\n";
			}

				
		}
		
		
		$file3 = JRequest::getVar( 'imagefile3', '', 'files', 'array' );

		if(isset($file3['name']) && $file3['name'] != '')
		{	
			jimport('joomla.filesystem.file');
			
			$safe3 = JFile::makesafe($file3['name']);
			$bads = array(" ", "?", "*", "+", "@", "#", "%", "$", "!", "&");
			$cleaned3 = str_replace($bads, "_", $safe3);
			$filename3 = JPATH_SITE . DS . 'images' . DS . 'content' . DS . 'arts_curriculum' . DS . 'masters'. DS. $cleaned3;	
			// make a dupe for dloads
			$dest = JPATH_SITE . DS . 'images' . DS . 'content' . DS . 'arts_curriculum' . DS . 'dloads'. DS. $cleaned3;
			JFile::copy($filename3, $dest);	
			if (!JFile::upload($file3['tmp_name'], $filename3)) {
				$this->msg = JText::_( 'Life is bad and the upload failed, check to make sure that /images/content/arts_curriculum/images/masters exists and is writable' );
				return;
			}
			// were' in the file system so upadte the DB		
			$db =& JFactory::getDBO();
			$query = "UPDATE #__arts_curriculum SET image3 = '$cleaned3' WHERE id = $this->id ";
			$db->setQuery( $query );
			if (!$db->query()) {
				echo "<script> alert('".$db->getErrorMsg()."'); window. history.go(-1); </script>\n";
			}

				
		}
		
		$file4 = JRequest::getVar( 'imagefile4', '', 'files', 'array' );

		if(isset($file4['name']) && $file4['name'] != '')
		{	
			jimport('joomla.filesystem.file');
			
			$safe4 = JFile::makesafe($file4['name']);
			$bads = array(" ", "?", "*", "+", "@", "#", "%", "$", "!", "&");
			$cleaned4 = str_replace($bads, "_", $safe4);
			$filename4 = JPATH_SITE . DS . 'images' . DS . 'content' . DS . 'arts_curriculum' . DS . 'masters'. DS. $cleaned4;	
			$dest = JPATH_SITE . DS . 'images' . DS . 'content' . DS . 'arts_curriculum' . DS . 'dloads'. DS. $cleaned4;
			JFile::copy($filename4, $dest);	
			if (!JFile::upload($file4['tmp_name'], $filename4)) {
				$this->msg = JText::_( 'Life is bad and the upload failed, check to make sure that /images/content/arts_curriculum/images/masters exists and is writable' );
				return;
			}
			// were' in the file system so upadte the DB		
			$db =& JFactory::getDBO();
			$query = "UPDATE #__arts_curriculum SET image4 = '$cleaned4' WHERE id = $this->id ";
			$db->setQuery( $query );
			if (!$db->query()) {
				echo "<script> alert('".$db->getErrorMsg()."'); window. history.go(-1); </script>\n";
			}

				
		}
		
		
		//pdf * files
		
		//let's handel the uploads - ugly but's it 's my first uploader
		
		$file = JRequest::getVar( 'asset1', '', 'files', 'array' );

		if(isset($file['name']) && $file['name'] != '')
		{	
			jimport('joomla.filesystem.file');
			
			$safe = JFile::makesafe($file['name']);
			$bads = array(" ", "?", "*", "+", "@", "#", "%", "$", "!", "&");
			$cleaned = str_replace($bads, "_", $safe);
			$filename = JPATH_SITE . DS . 'images' . DS . 'content' . DS . 'arts_curriculum' . DS . 'assets'. DS. $cleaned;	
			// were' in the file system so upadte the DB		
			$db =& JFactory::getDBO();
			$query = "UPDATE #__arts_curriculum SET asset1 = '$cleaned' WHERE id = $this->id ";
			$db->setQuery( $query );
			if (!$db->query()) {
				echo "<script> alert('".$db->getErrorMsg()."'); window. history.go(-1); </script>\n";
			}

				if (!JFile::upload($file['tmp_name'], $filename)) {
				$this->msg = JText::_( 'Life is bad and the upload failed, check to make sure that /images/content/arts_curriculum/images/assets exists and is writable' );
				return;
			}
		}
		
		$file = JRequest::getVar( 'asset2', '', 'files', 'array' );

		if(isset($file['name']) && $file['name'] != '')
		{	
			jimport('joomla.filesystem.file');
			
			$safe = JFile::makesafe($file['name']);
			$bads = array(" ", "?", "*", "+", "@", "#", "%", "$", "!", "&");
			$cleaned = str_replace($bads, "_", $safe);
			$filename = JPATH_SITE . DS . 'images' . DS . 'content' . DS . 'arts_curriculum' . DS . 'assets'. DS. $cleaned;	
			// were' in the file system so upadte the DB		
			$db =& JFactory::getDBO();
			$query = "UPDATE #__arts_curriculum SET asset2 = '$cleaned' WHERE id = $this->id ";
			$db->setQuery( $query );
			if (!$db->query()) {
				echo "<script> alert('".$db->getErrorMsg()."'); window. history.go(-1); </script>\n";
			}

				if (!JFile::upload($file['tmp_name'], $filename)) {
				$this->msg = JText::_( 'Life is bad and the upload failed, check to make sure that /images/content/arts_curriculum/images/assets exists and is writable' );
				return;
			}
		}
		
		
		$file = JRequest::getVar( 'asset3', '', 'files', 'array' );

		if(isset($file['name']) && $file['name'] != '')
		{	
			jimport('joomla.filesystem.file');
			
			$safe = JFile::makesafe($file['name']);
			$bads = array(" ", "?", "*", "+", "@", "#", "%", "$", "!", "&");
			$cleaned = str_replace($bads, "_", $safe);
			$filename = JPATH_SITE . DS . 'images' . DS . 'content' . DS . 'arts_curriculum' . DS . 'assets'. DS. $cleaned;	
			// were' in the file system so upadte the DB		
			$db =& JFactory::getDBO();
			$query = "UPDATE #__arts_curriculum SET asset3 = '$cleaned' WHERE id = $this->id ";
			$db->setQuery( $query );
			if (!$db->query()) {
				echo "<script> alert('".$db->getErrorMsg()."'); window. history.go(-1); </script>\n";
			}

				if (!JFile::upload($file['tmp_name'], $filename)) {
				$this->msg = JText::_( 'Life is bad and the upload failed, check to make sure that /images/content/arts_curriculum/images/assets exists and is writable' );
				return;
			}
		}
		
		$file = JRequest::getVar( 'asset4', '', 'files', 'array' );

		if(isset($file['name']) && $file['name'] != '')
		{	
			jimport('joomla.filesystem.file');
			
			$safe = JFile::makesafe($file['name']);
			$bads = array(" ", "?", "*", "+", "@", "#", "%", "$", "!", "&");
			$cleaned = str_replace($bads, "_", $safe);
			$filename = JPATH_SITE . DS . 'images' . DS . 'content' . DS . 'arts_curriculum' . DS . 'assets'. DS. $cleaned;	
			// were' in the file system so upadte the DB		
			$db =& JFactory::getDBO();
			$query = "UPDATE #__arts_curriculum SET asset4 = '$cleaned' WHERE id = $this->id ";
			$db->setQuery( $query );
			if (!$db->query()) {
				echo "<script> alert('".$db->getErrorMsg()."'); window. history.go(-1); </script>\n";
			}

				if (!JFile::upload($file['tmp_name'], $filename)) {
				$this->msg = JText::_( 'Life is bad and the upload failed, check to make sure that /images/content/arts_curriculum/images/assets exists and is writable' );
				return;
			}
		}
		
		// Now that that's all done check the table in so it can be edited.... we are done with it anyway
		$model->checkin();
	}
	
	
	function save()
	{
		$this->store() ;
		$link = 'index.php?option=com_arts_curriculum';
		$this->setRedirect( $link, $this->msg);
	}
	function apply()
	{
		$this->store() ;
		$link = 'index.php?option=com_arts_curriculum&view=item&task=edit&cid[]=' . $this->id ;
		$this->setRedirect($link, $this->msg);
	}
	function remove()
	{
		$cid = JRequest::getVar( 'cid', array(), 'post', 'array' );
		JArrayHelper::toInteger($cid);
		if (count( $cid ) < 1) {
			JError::raiseError(500, JText::_( 'Select an item to delete' ) );
		}
		$model = $this->getModel('item');
		if(!$model->delete($cid)) {
			echo "<script> alert('".$model->getError(true)."'); window.history.go(-1); </script>";
		}
		$this->setRedirect( 'index.php?option=com_arts_curriculum' );
	}

	function publish()
	{
		$cid = JRequest::getVar( 'cid', array(), 'post', 'array' );
		JArrayHelper::toInteger($cid);
		if (count( $cid ) < 1) {
			JError::raiseError(500, JText::_( 'Select an item to publish' ) );
		}
		$model = $this->getModel('item');
		if(!$model->publish($cid, 1)) {
			echo "<script> alert('".$model->getError(true)."'); window.history.go(-1); </script>";
		}
		$this->setRedirect( 'index.php?option=com_arts_curriculum' );
	}

	function unpublish()
	{
		$cid = JRequest::getVar( 'cid', array(), 'post', 'array' );
		JArrayHelper::toInteger($cid);
		if (count( $cid ) < 1) {
			JError::raiseError(500, JText::_( 'Select an item to unpublish' ) );
		}
		$model = $this->getModel('item');
		if(!$model->publish($cid, 0)) {
			echo "<script> alert('".$model->getError(true)."'); window.history.go(-1); </script>";
		}
		$this->setRedirect( 'index.php?option=com_arts_curriculum' );
	}
	function cancel()
	{
		// Checkin the item
		$model = $this->getModel('item');
		$model->checkin();
		$this->setRedirect( 'index.php?option=com_arts_curriculum' );
	}

	function orderup()
	{
		$model = $this->getModel('item');
		$model->move(-1);
		$this->setRedirect( 'index.php?option=com_arts_curriculum');
	}
	function orderdown()
	{
		$model = $this->getModel('item');
		$model->move(1);
		$this->setRedirect( 'index.php?option=com_arts_curriculum');
	}
	function saveorder()
	{
		$cid = JRequest::getVar( 'cid', array(), 'post', 'array' );
		$order = JRequest::getVar( 'order', array(), 'post', 'array' );
		JArrayHelper::toInteger($cid);
		JArrayHelper::toInteger($order);
		$model = $this->getModel('item');
		$model->saveorder($cid, $order);
		$msg = 'New ordering saved';
		$this->setRedirect( 'index.php?option=com_arts_curriculum', $msg );
	}
	
	// the big ugly image function
	/* method for making thumbnails
	 * this is jenky
	 * @ var mixed
	 * access public
		*/

	function makethumbs()
	{

		global $option, $mainframe;

		//First we'll access to the file system and we'll use the Joomla way to all safe.
		jimport('joomla.filesystem.file');
		$uploads_path = JPATH_ROOT . DS . "images". DS ."content" . DS ."arts_curriculum". DS . "masters" ;
		$thumb_path = JPATH_ROOT . DS . "images". DS ."content" . DS ."arts_curriculum". DS . "thumbs" ;

		// this is the width in px that we're telling GD to scale to, where's imagemagik whe you need it.
		$new_w = 90;
		// where our source images live b/c GD needs to read them
		$cfg_fullsizepics_path = $uploads_path;
		//where we're sending them when we are done
		$cfg_thumb_path = $thumb_path;
		// we need one more path for this to work
		$filepath = $uploads_path ;
		// the directory
		$dir = dir($filepath);

		//check folders
			
		while($entry=$dir->read()) {
			//check the files
			if($entry == "." || $entry == "..") {

				continue;
			}
				
			$fp = @fopen("$filepath/$entry","r");

			$photo_filename = "$entry";

			$image_stats = GetImageSize($cfg_fullsizepics_path."/".$entry);

			$imagewidth = $image_stats[0];

			$imageheight = $image_stats[1];

			$img_type = $image_stats[2];

			$ratio = ($imagewidth / $new_w);

			$new_h = round($imageheight / $ratio);

			if (!file_exists($cfg_thumb_path."/".$entry))  {

				if ($img_type=="2") {

					$src_img = imagecreatefromjpeg($cfg_fullsizepics_path."/".$entry);

					$dst_img = imagecreatetruecolor($new_w,$new_h);

					imagecopyresampled($dst_img,$src_img,0,0,0,0,$new_w,$new_h,imagesx($src_img),imagesy($src_img));

					imagejpeg($dst_img, "$cfg_thumb_path"."/$entry", 100);
						
					imagedestroy($dst_img);

				} elseif  ($img_type=="3") {

					$src_img=ImageCreateFrompng($cfg_fullsizepics_path."/".$entry);
					 
					$dst_img=ImageCreateTrueColor($new_w,$new_h);
						
					ImageCopyResampled($dst_img,$src_img,0,0,0,0,$new_w,$new_h,ImageSX($src_img),ImageSY($src_img));

					Imagepng($dst_img, "$cfg_thumb_path"."/$entry",100);

					imagedestroy($dst_img);

				} elseif  ($img_type=="1") {

					$cfg_thumb_url=$cfg_fullsizepics_url;

				} 

			}



		} //the files are now in the /images/content/arts_curriculum/thumbs directory

		$this->setRedirect( 'index.php?option=' . $option. '&task=makesitesmages&controller=items' , 'Thumbnails are made' );


	} // the end of thumbnail creation
	
	
	
		/* function to make thumbnails using
		* @ string
	 	*  returns bolean
		**/

		function thumbMaker($image_to_make){
		
		global $option, $mainframe;
		
		//contants for size and quality
		$h_targ_w = 120;
		$v_targ_h = 120;
		$jpeg_quality = 100;
		
		// where the masters live 
		$uploads_path = JPATH_ROOT . DS . "images". DS ."content" . DS ."arts_curriculum". DS . "masters" ;
		// where the files will be placed
		$thumb_path = JPATH_ROOT . DS . "images". DS ."content" . DS ."arts_curriculum". DS . "thumbs" ;
		//get some info from image
		$image_stats = GetImageSize($image_to_make);
		$imagewidth = $image_stats[0];
		$imageheight = $image_stats[1];
		
		// conditions for orientation - horizontal
		if ($imagewidth > $imageheight) {
		
			//do math to determine height
			$ratio = ($imagewidth / $h_targ_w);
			$new_h = round($imageheight / $ratio);
			
			$src_img = imagecreatefromjpeg($uploads_path."/".$image_to_make);
			$dst_img = imagecreatetruecolor($v_targ_w,$new_h);
		
			imagecopyresampled($dst_img,$src_img,0,0,0,0,$h_targ_w,$new_h,imagesx($src_img),imagesy($src_img));
			imagejpeg($dst_img, "$thumb_path"."/$image_to_make", $jpeg_quality);						
			imagedestroy($dst_img);
			}
		
		// conditions for orientation - vertical
		if ($imageheight >$imageheight) {
		
			//do math to determine width
			$ratio = ($imageheight / $v_targ_h);
			$new_w = round($imagewidth / $ratio);
			
			$src_img = imagecreatefromjpeg($uploads_path."/".$image_to_make);
			$dst_img = imagecreatetruecolor($new_w,$v_tag_h);
		
			imagecopyresampled($dst_img,$src_img,0,0,0,0,$new_w,$v_targ_h,imagesx($src_img),imagesy($src_img));
			imagejpeg($dst_img, "$thumb_path"."/$image_to_make", $jpeg_quality);
			imagedestroy($dst_img);
			
			}
		
		
		return true;
		
		}

}// the end

